#!/bin/bash

set +e

if [ -z $2 ]; then
  error "Please set the notary and migrate version"
  exit 1
fi

echo "Building notary and golang-migrate from source, notary version: $1, golang-migrate version: $2"
set -e

# the temp folder to store binary file...
mkdir -p binary
rm -rf binary/* || true

cd `dirname $0`
docker build --build-arg NOTARY_VERSION=$1 --build-arg MIGRATE_VERSION=$2 -f ./binary.Dockerfile -t notary-binary .

echo 'copy the binary files to local...'
ID=$(docker create notary-binary)
docker cp $ID:/go/bin/notary-server binary/
docker cp $ID:/go/bin/notary-signer binary/
docker cp $ID:/go/bin/migrate binary/
docker cp $ID:/migrations binary/

sed -i 's/waiting for $DB_URL/waiting for database/g' binary/migrations/migrate.sh

docker rm -f $ID
docker rmi -f notary-binary

